package com.inforest.ui;

import com.inforest.model.User;
import com.inforest.service.UserService;

import java.util.*;

public class CliUI {
    private final UserService service = new UserService();
    private final Scanner scanner = new Scanner(System.in);

    public CliUI() {
        initSampleData();
    }

    private void initSampleData() {
        List<User> sampleUsers = new ArrayList<>();
        sampleUsers.add(new User("张三", "Male", 25, "zhangsan@example.com", "13800138001"));
        sampleUsers.add(new User("李四", "Female", 28, "lisi@example.com", "13800138002"));
        sampleUsers.add(new User("王五", "Male", 30, "wangwu@example.com", "13800138003"));
        for (User user : sampleUsers) {
            service.addUser(user);
        }
        System.out.println("示例数据初始化完成");
    }

    public void start() {
        System.out.println("用户管理系统启动（输入 help 查看命令帮助）");

        while (true) {
            System.out.print("\n> ");
            String input = scanner.nextLine().trim();
            if (input.isEmpty()) continue;

            String[] args = input.split(" ");
            try {
                switch (args[0]) {
                    case "user":
                        handleUserCommand(args);
                        break;
                    case "exit":
                        System.out.println("系统退出");
                        return;
                    case "help":
                        printHelp();
                        break;
                    default:
                        System.out.println("未知命令：" + args[0]);
                        break;
                }
            } catch (Exception e) {
                System.out.println("错误: " + e.getMessage());
            }
        }
    }

    private void handleUserCommand(String[] args) {
        if (args.length < 2) {
            throw new IllegalArgumentException("命令不完整，输入 help 查看用法");
        }

        switch (args[1]) {
            case "add":
                addUserFlow(args);
                break;
            case "delete":
                deleteUserFlow(args);
                break;
            case "list":
                listUsersFlow();
                break;
            case "update":
                updateUserFlow(args);
                break;
            default:
                throw new IllegalArgumentException("未知 user 子命令: " + args[1]);
        }
    }

    private void addUserFlow(String[] args) {
        Map<String, String> params = parseParams(args);
        try {
            User user = new User(
                    params.get("name"),
                    params.get("gender"),
                    Integer.parseInt(params.get("age")),
                    params.get("email"),
                    params.get("phone")
            );
            service.addUser(user);
            System.out.println("用户添加成功，ID: " + user.getId());
        } catch (Exception e) {
            throw new IllegalArgumentException("添加失败，请确保参数完整且格式正确：--name --gender --age --email --phone");
        }
    }

    private void deleteUserFlow(String[] args) {
        Map<String, String> params = parseParams(args);
        String idStr = params.get("id");
        if (idStr == null) {
            throw new IllegalArgumentException("缺少用户ID参数，使用格式：user delete --id <用户ID>");
        }

        try {
            int id = Integer.parseInt(idStr);
            String deleted = service.deleteUser(id);
            if (deleted == null) {
                System.out.println("用户不存在，ID: " + id);
            } else {
                System.out.println("用户删除成功");
            }
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("用户ID必须是数字");
        }
    }

    private void listUsersFlow() {
        List<User> users = service.listUsers();
        if (users.isEmpty()) {
            System.out.println("当前没有用户");
            return;
        }

        System.out.println("用户列表：");
        for (User user : users) {
            System.out.printf(
                    "ID: %d, 姓名: %s, 性别: %s, 年龄: %d, 邮箱: %s, 电话: %s%n",
                    user.getId(), user.getName(), user.getGender(),
                    user.getAge(), user.getEmail(), user.getPhone()
            );
        }
    }

    private void updateUserFlow(String[] args) {
        Map<String, String> params = parseParams(args);
        String idStr = params.get("id");
        if (idStr == null) {
            throw new IllegalArgumentException("缺少用户ID参数，使用格式：user update --id <用户ID>");
        }

        try {
            int id = Integer.parseInt(idStr);
            User existing = service.getUser(id);
            if (existing == null) {
                throw new IllegalArgumentException("用户不存在，ID: " + id);
            }

            User updated = new User(
                    params.containsKey("name") ? params.get("name") : existing.getName(),
                    params.containsKey("gender") ? params.get("gender") : existing.getGender(),
                    params.containsKey("age") ? Integer.parseInt(params.get("age")) : existing.getAge(),
                    params.containsKey("email") ? params.get("email") : existing.getEmail(),
                    params.containsKey("phone") ? params.get("phone") : existing.getPhone()
            );
            updated.setId(id);

            service.updateUser(id, updated);
            System.out.println("用户信息更新成功");
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("用户ID 和 年龄必须是数字");
        }
    }

    private Map<String, String> parseParams(String[] args) {
        Map<String, String> params = new HashMap<>();
        for (int i = 2; i < args.length; i++) {
            if (args[i].startsWith("--")) {
                String key = args[i].substring(2);
                if (i + 1 < args.length && !args[i + 1].startsWith("--")) {
                    params.put(key, args[++i]);
                } else {
                    throw new IllegalArgumentException("参数值缺失：" + key);
                }
            }
        }
        return params;
    }

    private void printHelp() {
        System.out.println(
                "可用命令：\n" +
                        "user list\n" +
                        "    查看所有用户\n\n" +
                        "user add --name <姓名> --gender <性别> --age <年龄> --email <邮箱> --phone <电话>\n" +
                        "    添加新用户\n\n" +
                        "user delete --id <用户ID>\n" +
                        "    删除用户\n\n" +
                        "user update --id <用户ID> [--name <姓名>] [--gender <性别>] [--age <年龄>] [--email <邮箱>] [--phone <电话>]\n" +
                        "    更新用户信息\n\n" +
                        "exit\n" +
                        "    退出系统\n"
        );
    }
}
